﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using umbraco.controls;
using umbraco.uicontrols;
using umbraco;
using umbraco.BasePages;
using System.Collections.Generic;

namespace tswe.log
{
    public partial class deleteLog : System.Web.UI.UserControl
    {
        # region members

        protected datePicker datePicker;

        # endregion members

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getLogs();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            if (Parent is TabPage)
                InitControlItems();
            base.OnInit(e);
        }

        public void InitControlItems()
        {
            datePicker = new datePicker();
            datePicker.ShowTime = false;
            datePicker.EmptyDateAsDefault = false;
            datePicker.ID = "dpBeforeDate";
            content.Controls.Add(datePicker);
            initDatePicker();

            TabPage tp = this.Parent as TabPage;

            ImageButton refresh = tp.Menu.NewImageButton();
            refresh.ImageUrl = GlobalSettings.Path + "/plugins/tswe/log/images/refresh.png";
            refresh.CommandName = "refresh";
            refresh.AlternateText = "Refresh";
            refresh.Command += new CommandEventHandler(refresh_Command);

            ImageButton delete = tp.Menu.NewImageButton();
            delete.ImageUrl = GlobalSettings.Path + "/plugins/tswe/log/images/delete.png";
            delete.CommandName = "delete";
            delete.AlternateText = "Delete";
            delete.Attributes.Add("onClick", "return confirmDelete (this.form);");
            delete.Command += new CommandEventHandler(delete_Command);
        }

        private void initDatePicker()
        {
            datePicker.DateTime = DateTime.Now.AddDays(-60);
        }

        private int getDatePickerDays()
        {
            if (datePicker.DateTime < new DateTime(2000, 01, 01))
                initDatePicker();

            return (DateTime.Now - datePicker.DateTime).Days;
        }

        void refresh_Command(object sender, CommandEventArgs e)
        {
            getLogs();
        }

        void delete_Command(object sender, CommandEventArgs e)
        {
            deleteLogs();
        }

        private void deleteLogs()
        {
            string logHeaders = "";
            bool anySelected = false;
            foreach (DataGridItem item in logGrid.Items)
            {
                CheckBox box = (CheckBox)item.FindControl("DeleteThis");
                if (box.Checked)
                {
                    anySelected = true;
                    logHeaders = logHeaders + "'" + ((TableCell)item.Cells[1]).Text.ToString() + "',";
                }
            }
            if (anySelected)
            {
                logHeaders = logHeaders.Substring(0, logHeaders.LastIndexOf(","));
                int iDays = getDatePickerDays();
                DateTime beforeDate = DateTime.Now - new TimeSpan(iDays, 0, 0, 0);
                try
                {
                    int count = sqlHelper.ExecuteScalar<int>(@"select count(*) from umbracoLog 
                        where DateStamp < @dateStamp
                        and logHeader in (" + logHeaders + ")",
                        sqlHelper.CreateParameter("@dateStamp", beforeDate));

                    sqlHelper.ExecuteNonQuery(@"delete from umbracoLog 
                        where DateStamp < @dateStamp
                        and logHeader in (" + logHeaders + ")",
                        sqlHelper.CreateParameter("@dateStamp", beforeDate));

                    string message = String.Format(
                        "{0} log type entries have been deleted.", count);
                    Log.Add(LogTypes.Delete, getUser(), -1, message);
                    if (Page is BasePage)
                    {
                        //Okay we are in Umbraco
                        ((BasePage)Page).speechBubble(BasePage.speechBubbleIcon.success, 
                            "Delete successful", message);
                    }
                }
                catch (Exception e)
                {
                    string message = String.Format("Exception at delete log entries: {0}", e.Message);
                    Log.Add(LogTypes.Error, getUser(), -1, message);
                    if (Page is BasePage)
                    {
                        //Okay we are in Umbraco
                        ((BasePage)Page).speechBubble(BasePage.speechBubbleIcon.error, "Delete Error",
                            "Unable to delete selected log entries. Check the log.");
                    }
                }
                getLogs();
            }
        }

        private User getUser()
        {
            if (Page is BasePage)
                //Okay we are in Umbraco
                return ((BasePage)Page).getUser();
            else
                return User.GetUser(0);
        }

        private void getLogs()
        {
            int iDays = getDatePickerDays();
            lblDays.Text = iDays.ToString();
            DateTime beforeDate = DateTime.Now - new TimeSpan(iDays, 0, 0, 0);

            DataTable table = new DataTable();
            table.Columns.Add("logHeader", typeof(string));
            table.Columns.Add("logCount", typeof(int));

            // list all log types sorted
            SortedList<string, LogTypes> logTypes = new SortedList<string, LogTypes>();
            foreach (LogTypes types in Enum.GetValues(typeof(LogTypes)))
            {
                logTypes.Add(types.ToString(), types);
            }

            foreach (KeyValuePair<string, LogTypes> kvp in logTypes)
            {
                int count = getLogTypesCount(kvp.Value, beforeDate);
                if (count == 0) continue;
                DataRow row = table.NewRow();
                row["logHeader"] = kvp.Key;
                row["logCount"] = count.ToString();
                table.Rows.Add(row);
            }
            this.logGrid.DataSource = table;
            this.logGrid.DataBind();
            pp_LogTable.Visible = (table.Rows.Count > 0);
        }

        private static ISqlHelper sqlHelper
        {
            get { return umbraco.BusinessLogic.Application.SqlHelper; }
        }

        private int getLogTypesCount(LogTypes logType, DateTime beforeDate)
        {
            return sqlHelper.ExecuteScalar<int>(
                @"select count(*) from umbracoLog 
                where logHeader = @logHeader and DateStamp < @dateStamp",
                sqlHelper.CreateParameter("@logHeader", logType.ToString()),
                sqlHelper.CreateParameter("@dateStamp", beforeDate));
        }
    }
}